package net.zjitc.service.impl;

import net.zjitc.mapper.AdminMapper;
import net.zjitc.mapper.SettingMapper;
import net.zjitc.service.SettingService;
import net.zjitc.utils.Md5;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

@Service
@Transactional
public class SettingServiceImpl implements SettingService {
    @Autowired
    private SettingMapper settingMapper;

    @Autowired
    private AdminMapper adminMapper;

    @Override
    public int changePassword(String username, String oldPassword, String newPassword, String newPassword2) {
        // 验证新密码是否一致
        if (!newPassword.equals(newPassword2)) {
            return 1;
        }

        if(newPassword.equals(oldPassword)){
            return 2;
        }

        String salt = adminMapper.login(username).getSalt();
        newPassword = Md5.hashPassword(newPassword, salt);
        oldPassword = Md5.hashPassword(oldPassword, salt);

        // 验证旧密码是否正确
        String password = adminMapper.login(username).getPassword();
        if(!Objects.equals(oldPassword, password)){
            //输出错误提示
            return 3;
        }

        // 执行更新操作并获取受影响的行数
        int rowsAffected = settingMapper.changePassword(username,newPassword);

        // 如果受影响的行数大于0，表示更新成功
        if(rowsAffected > 0){
            return 0;
        }else{
            return 4;
        }
    }

    @Override
    public int changeAvatar(String username, String avatar) {
        System.out.println(username);
        System.out.println(avatar);
        int admin = settingMapper.changeAvatar(username, avatar);
        if (admin > 0) {
            return 0;
        }
        return 1;

    }
}



